<template>
  <div>
    <!--  顶部面包屑  -->
    <div class="ccui-navigation">
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回
      </el-button>
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}
        </el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/invoice/Entering/toSubmit' }"
          >发票管理
        </el-breadcrumb-item>
        <el-breadcrumb-item
          :to="{
            path: '/invoice/Entering/toSubmit'
          }"
          >发票录入
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span>编辑</span>
          <span style="margin-left: 10px; color: #4a4a4a">{{
            $route.query.invoiceName
          }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs v-model="activeName" class="el-tabs__customize">
          <el-tab-pane label="基本信息" name="a">
            <basicInfo
              class="commonClass"
              ref="basicInfo"
              :form="basicForm"
              :myId="myId"
              @clearTable="clearTable"
              @settlementCoder="settlementCoder"
            ></basicInfo>
          </el-tab-pane>

          <el-tab-pane label="发票清单" name="b">
            <invoiceTableBill
              class="commonClass"
              ref="invoiceBillList"
              :basicForm="basicForm"
              :tableBill="invoiceBillList"
              @fixMoney="fixMoney"
              :isAdd="isAdd"
              @businessType="businessType"
            />
          </el-tab-pane>

          <el-tab-pane label="发票信息" name="c">
            <invoiceTableInfo
              class="commonClass"
              ref="invoiceInfoList"
              :tableInfo="invoiceInfoList"
            />
          </el-tab-pane>

          <el-tab-pane label="款项明细" name="d">
            <paymentDetails
              class="commonClass"
              ref="paymentDetails"
              :paymentDetails="paymentDetail"
            />
          </el-tab-pane>

          <el-tab-pane label="附件" name="e">
            <attachment
              ref="attachment"
              :parentData="fileList"
              class="commonClass"
              v-if="flag"
            ></attachment>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide v-if="$route.query.enterStatus == '审批退回'">
      <ul class="ccui-bottom-button">
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('save')"
            >保存并校验
          </el-button>
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('submit')"
            >保存并提交
          </el-button>
        </li>
        <div class="ccui-bottom-guide-divider" />
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回
          </el-button>
        </li>
      </ul>
    </el-bottom-guide>
    <el-bottom-guide v-else>
      <ul class="ccui-bottom-button">
        <li>
          <el-button type="bottom" icon="icon-ccui-save" @click="timeKeep()"
            >暂存
          </el-button>
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('save')"
            >保存并校验
          </el-button>
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('submit')"
            >保存并提交
          </el-button>
        </li>
        <div class="ccui-bottom-guide-divider" />
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回
          </el-button>
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import basicInfo from "../components/basicInfo";
import invoiceTableBill from "../components/invoiceTableBill";
import invoiceTableInfo from "../components/invoiceTableInfo";
import paymentDetails from "../components/paymentDetails";
import attachment from "@/basa/components/public/uploadInfo2";

import { ishasAgentId } from "@/basa/utils";
import {
  editInvoceBasic,
  getInvoceBasicById,
  submitInvoice,
  tempEditInvoceBasic
} from "../api";
import { getSettlementById } from "../../../settlement-management/settlement-written-off/api/settlement-written-off";
import { formatNumber } from "../../../../basa/utils";

export default {
  name: "invoice_edit",
  components: {
    basicInfo,
    invoiceTableBill,
    invoiceTableInfo,
    paymentDetails,
    attachment
  },
  data() {
    return {
      basicForm: {
        reportInOrgName: "",
        partyBName: "",
        invoiceCode: "",
        invoiceName: "",
        settlementCode: "",
        settlementName: "",
        categoryName: "",
        currency: "",
        settlementAmount: "",
        totalInvoiceAmount: "",
        currentInvoiceAmount: "",
        invoiceNum: "",
        compileUser: "",
        compileDate: "",
        remark: "",
        businessType: ""
      },
      invoiceBillList: [],
      invoiceInfoList: [],
      paymentDetail:[],
      fileList: [],
      activeName: "a",
      submitFlag: false, // 缓存
      myId: "",
      showMessage: "",
      fileData: [],
      codeer: "",
      flag: false,
      isAdd: false,
      c: ""
    };
  },
  methods: {
    clearTable() {
      this.invoiceBillList = [];
      // this.invoiceInfoList= []
      this.fileList = [];
    },
    fixMoney(data) {
      this.showMessage = data;
    },
    settlementCoder(data) {
      console.log("settlementCoder>>>>", data);
      if (this.codeer !== data) {
        this.invoiceBillList = [];
        // this.$refs.invoiceInfoList.tableData=[];
        this.codeer = data;
      }
    },
    businessType(data) {
      this.businessValue = data;
    },

    // 保存 提交
    submitHandle(name) {
      // this.getValidate(this.$refs.contractList.tableData);
      this.$refs.basicInfo.$refs.basicInfo.validate(valid => {
        console.log(valid, "validvalid");
        if (valid) {
          // if (this.contractListBool) {
          var totalAmount = Number(0);
          for (let i = 0; i < this.invoiceInfoList.length; i++) {
            totalAmount += Number(this.invoiceInfoList[i].priceTaxTotal);
          }
          this.basicForm.amount = totalAmount;
          let arrNum = this.$refs.attachment.fileList.length;
          for (let i = 0; i < arrNum; i++) {
            this.fileData[i] = {};
            this.fileData[i].uploadTime = this.$refs.attachment.fileList[
              i
            ].createTime;
            this.fileData[i].uploadId = this.$refs.attachment.fileList[
              i
            ].uploadId;
            this.fileData[i].fileDesc = this.$refs.attachment.fileList[
              i
            ].fileDesc;
          }
          // 调接口
          if (name == "save") {
            this.saveInvoice();
          } else {
            this.submitInvoice();
          }
          // this.listPcConcSubByState();
          // this.listPcConcSubProtocolByState();
        } else {
          // 弹个窗
          console.log("else失败, 弹窗");
          //   this.$message({
          //     type: "error",
          //     message: ",
          //     showClose: true,
          //     ccuiCustom: true
          //   });
          this.$showErrorMessage("发票单基本信息不完整，请编辑后保存");
        }
      });
    },
    handleBack() {
      this.$router.push(
        sessionStorage.getItem("fromPath") || "/invoice/Entering/toSubmit"
      );
    },
    timeKeep() {
      this.$refs.basicInfo.form.compileDate = this.basicGetDate;

      this.$refs.invoiceBillList.tableData.forEach(e => {
        if (e.id) {
          for (let i = 0; i < this.invoiceBillList.length; i++) {
            if (e.id == this.invoiceBillList[i].id) {
              e.amountExcludeTaxFirst = this.invoiceBillList[
                i
              ].amountExcludeTaxFirst;
              e.taxFirst = this.invoiceBillList[i].taxFirst;
            }
          }
        }
      });

      this.$refs.invoiceInfoList.tableData.forEach(e => {
        if (typeof e.id == "string") {
          delete e.id;
        }
      });
      let arrNum = this.$refs.attachment.fileList.length;
      for (let i = 0; i < arrNum; i++) {
        this.fileData[i] = {};
        this.fileData[i].uploadTime = this.$refs.attachment.fileList[
          i
        ].createTime;
        this.fileData[i].uploadId = this.$refs.attachment.fileList[i].uploadId;
        this.fileData[i].fileDesc = this.$refs.attachment.fileList[i].fileDesc;
      }
      this.$refs.invoiceBillList.tableData.forEach((e, index) => {
        e.sn = index;
        e.settlementListId = e.id;
      });
      var obj = {
        invoceBasic: this.$refs.basicInfo.form,
        invoceBill: this.$refs.invoiceBillList.tableData,
        invoceInfo: this.$refs.invoiceInfoList.tableData,
        // fileInfoIds: this.$refs.attachment.uploadIds
        //  fileReqBOS: this.fileData
        files: this.fileData,
        businessType: this.$refs.basicInfo.form.businessType
      };
      tempEditInvoceBasic(obj).then(res => {
        console.log(res.data);
        if (res.data.code == "0") {
          this.$message({
            type: "success",
            message: res.data.message,
            showClose: true,
            ccuiCustom: true,
            duration: 3000
          });
          this.$router.go(-1);
        }
      });
      this.fileData = [];
    },
    saveInvoice() {
      let baseInfo = this.$refs.basicInfo.form;
      baseInfo = delete this.$refs.basicInfo.form.settlement;
      this.$refs.basicInfo.form.compileDate = this.basicGetDate;
      console.log(baseInfo);
      this.$refs.invoiceBillList.tableData.forEach((e, index) => {
        e.sn = index;
        e.rate = e.taxRate;
        e.settlementListId = e.id;

        for (let i = 0; i < this.invoiceBillList.length; i++) {
          if (e.id == this.invoiceBillList[i].id) {
            e.amountExcludeTaxFirst = this.invoiceBillList[
              i
            ].amountExcludeTaxFirst;
            e.taxFirst = this.invoiceBillList[i].taxFirst;
          }
        }
      });
      this.$refs.invoiceInfoList.tableData.forEach(e => {
        if (typeof e.id == "string") {
          delete e.id;
        }
      });
      let invoiceDateInfo = this.$refs.invoiceInfoList.tableData.every(item => {
        return item.invoiceDate;
      });
      console.log(invoiceDateInfo);
      // if(invoiceDateInfo == false){
      //     this.$showErrorMessage('发票信息开票日期必填')
      //     return;
      // }
      this.$refs.basicInfo.form.compileDate = Date.parse(
        this.$refs.basicInfo.form.compileDate
      );
      var obj = {
        invoceBasic: this.$refs.basicInfo.form,
        invoceBill: this.$refs.invoiceBillList.tableData,
        invoceInfo: this.$refs.invoiceInfoList.tableData,
        // fileInfoIds: this.$refs.attachment.uploadIds
        //  fileReqBOS: this.fileData
        files: this.fileData,
        businessType: this.$refs.basicInfo.form.businessType
      };
      editInvoceBasic(obj).then(res => {
        this.$message({
          type: "success",
          message: res.data.message,
          showClose: true,
          ccuiCustom: true,
          duration: 3000
        });
        this.$router.go(-1);
      });
      this.fileData = [];
    },
    submitInvoice() {
      this.$refs.basicInfo.form.compileDate = this.basicGetDate;

      this.$refs.invoiceBillList.tableData.forEach((e, i) => {
        e.contractBillId = e.materialId;
        e.sn = i;
        e.rate = e.taxRate;
        e.settlementListId = e.id;

        for (let i = 0; i < this.invoiceBillList.length; i++) {
          if (e.id == this.invoiceBillList[i].id) {
            e.amountExcludeTaxFirst = this.invoiceBillList[
              i
            ].amountExcludeTaxFirst;
            e.taxFirst = this.invoiceBillList[i].taxFirst;
          }
        }
      });
      this.$refs.invoiceInfoList.tableData.forEach(e => {
        if (typeof e.id == "string") {
          delete e.id;
        }
      });

      this.$refs.basicInfo.form.compileDate = Date.parse(
        this.$refs.basicInfo.form.compileDate
      );
      let invoiceDateInfo = this.$refs.invoiceInfoList.tableData.every(item => {
        return item.invoiceDate;
      });
      console.log(invoiceDateInfo);
      // if (invoiceDateInfo == false) {
      //     this.$showErrorMessage('发票信息开票日期必填');
      //     return;
      // }
      // this.$refs.invoiceInfoList.tableData.forEach(e=>{
      //     // e.invoiceDate=Date.parse(e.invoiceDate)
      //      let date = new Date(e.invoiceDate); //由于Date.parse 转换数据出现NAN  导致提交时，时间报错，自动置空;
      //       var y = date.getFullYear();
      //       var m = date.getMonth() + 1;
      //       m = m < 10 ? "0" + m : m;
      //       var d = date.getDate();
      //       d = d < 10 ? "0" + d : d;
      //       e.invoiceDate =  y + "-" + m + "-" + d;
      // })
      var obj = {
        invoceBasic: this.$refs.basicInfo.form,
        invoceBill: this.$refs.invoiceBillList.tableData,
        invoceInfo: this.$refs.invoiceInfoList.tableData,
        // fileInfoIds: this.$refs.attachment.uploadIds
        // fileReqBOS: this.fileData
        files: this.fileData,
        businessType: this.$refs.basicInfo.form.businessType
      };
      submitInvoice(obj).then(res => {
        this.$message({
          type: "success",
          message: res.data.message,
          showClose: true,
          ccuiCustom: true,
          duration: 3000
        });
        this.$router.go(-1);
      });
      this.fileData = [];
    }
  },
  formatDateTime(date) {
    console.log(date);
    let _time = new Date(date);
    var y = _time.getFullYear();
    var m = _time.getMonth() + 1;
    m = m < 10 ? "0" + m : m;
    var d = _time.getDate();
    d = d < 10 ? "0" + d : d;
    return y + "-" + m + "-" + d;
  },
  activated() {
    this.id = this.$route.params.id;
    getInvoceBasicById({
      id: this.id
    }).then(res => {
      //   res.data.data.invoceBasic.compileDate = res.data.data.invoceBasic.compileDate.substring(
      //     0,
      //     11
      //   );
      this.basicForm = res.data.data.invoceBasic; //基本信息
      // 编辑时候选择结算单判断值
      this.$bus.$emit(
        "settlementBasicName",
        res.data.data.invoceBasic.settlementName
      );
      this.$bus.$emit(
        "settlementBasicCode",
        res.data.data.invoceBasic.settlementCode
      );
      this.$bus.$emit(
        "settlementBasicId",
        res.data.data.invoceBasic.settlementId
      );

      this.$bus.$emit("settlementCoder", this.basicForm.settlementId);
      this.basicForm.compileDate = this.basicForm.compileDate
        ? this.basicForm.compileDate.substring(0, 11)
        : "";
      this.basicGetDate = this.basicForm.compileDate; //储存时间

      this.basicForm.settlementAmount = Number(
        this.basicForm.settlementAmount
      ).toFixed(2);
      this.basicForm.totalInvoiceAmount = Number(
        this.basicForm.totalInvoiceAmount
      ).toFixed(2);
      this.basicForm.currentInvoiceAmount = Number(
        this.basicForm.currentInvoiceAmount
      ).toFixed(2);
      // if(this.basicForm.invoiceNum){
      //     this.basicForm.invoiceNum=formatNumber(this.basicForm.invoiceNum,3)
      // }

      this.invoiceBillList = res.data.data.invoceBill; //发票清单
      this.invoiceBillList.forEach(e => {
        if (e.currentNum) {
          e.currentNum = formatNumber(e.currentNum, 3);
        }

        e.unitPriceWithoutTax = Number(e.unitPriceWithoutTax).toFixed(2);
        e.price = Number(e.price).toFixed(2);
        e.amountExcludeTax = Number(e.amountExcludeTax).toFixed(2);
        e.tax = Number(e.tax).toFixed(2);
        e.amount = Number(e.amount).toFixed(2);
      });

      //   res.data.data.invoceInfo.compileDate = res.data.data.invoceInfo.compileDate.substring(
      //     0,
      //     11
      //   );
      this.invoiceInfoList = res.data.data.invoceInfo; //发票信息
      this.invoiceInfoList.forEach(e => {
        if (e.invoiceDate) {
          let data = e.invoiceDate.substring(0, 11);
          e.invoiceDate = data;
        }
        if (e.amountExcludeTax) {
          e.amountExcludeTax = e.amountExcludeTax.toFixed(2);
        }
        if (e.priceTaxTotal) {
          e.priceTaxTotal = e.priceTaxTotal.toFixed(2);
        }
        if (e.tax) {
          e.tax = e.tax.toFixed(2);
        }
        // e.rate = new this.$BigNumber(Number(e.rate)).multipliedBy(100) + "%";
      });
      this.paymentDetail = res.data.data.paymentDetail;//款项明细
      this.fileList = res.data.data.files; //附件信息

      this.fileList.forEach(item => {
        item.createTime = item.uploadTime;
        // item.fileSize =
        //   item.fileSize.substr(0, item.fileSize.length - 3) + "KB";
        item.uploadId = item.fileInfoId;
      });
      console.log("附件信息", this.fileList);
      this.flag = true;
      // var fileIds = [];
      // for (let i = 0; i < this.fileList.length; i++) {
      //   fileIds.push(this.fileList[i].fileInfoId);
      // }
      // this.$refs.attachment.uploadIds = fileIds;
      var fileIds = [];
      for (let i = 0; i < this.fileList.length; i++) {
        fileIds[i] = {};
        fileIds[i].fileDesc = this.fileList[i].fileDesc;
        fileIds[i].fileInfoId = this.fileList[i].fileInfoId;
        fileIds[i].uploadId = this.fileList[i].uploadId;
        fileIds[i].uploadTime = this.fileList[i].uploadTime;
        fileIds[i].createTime = this.fileList[i].uploadTime;
        fileIds[i].fileName = this.fileList[i].fileName;
        fileIds[i].fileSize = this.fileList[i].fileSize;
      }
      //如果没有附件会导致找不到fileList，阻断程序，导致settlement找不到，在编辑时无法更换入库单
      this.$nextTick(() => {
        this.$refs.attachment.fileList = fileIds;
      });

      getSettlementById({
        ids: [this.basicForm.settlementId]
      }).then(res => {
        this.basicForm.settlement = res.data.data;
        this.$bus.$emit("businessType", res.data.data.settlement.businessType);
      });
    });
    this.activeName = "a";
  },
  // deactivated(){
  //   this.$nextTick(() =>{
  //     this.fileList = []
  //   })
  // },
  created() {
    this.myId = this.$route.params.id;
  },
  mounted() {
    console.log(this.$route.query.enterStatus);
  },
  beforeRouteEnter(to, from, next) {
    !(to.fullPath === from.fullPath) &&
      sessionStorage.setItem("fromPath", from.fullPath);
    next();
  },
  // 更改列表缓存状态
  beforeRouteLeave(to, from, next) {
    // if (this.submitFlag === true) {
    for (var key in this.$vnode.parent.parent.componentInstance.cache) {
      delete this.$vnode.parent.parent.componentInstance.cache[
        ishasAgentId(to.path, key)
      ];
    }
    // }
    next();
  }
};
</script>

<style scoped lang="scss">
.commonClass {
  margin-top: 5px;
}

/deep/ .el-group-title .group-content {
  margin-top: 40px;
}
</style>
